@ECHO OFF
SETLOCAL

REM 设置当前脚本所在的目录为变量
SET "SCRIPT_DIR=%~dp0"

REM 调用Visual Studio 2017 Enterprise的vcvarsall.bat来设置环境变量
CALL "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" x64
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to set up Visual Studio 2017 Enterprise environment
    PAUSE
    EXIT /B 1
)

REM 将Strawberry Perl相关的目录添加到PATH
SET "PATH=%SCRIPT_DIR%Strawberry5.38.2.2\c\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\site\bin;%SCRIPT_DIR%Strawberry5.38.2.2\perl\bin;%PATH%"

REM 将jom的目录添加到PATH
SET "PATH=%SCRIPT_DIR%jom_1_1_4;%PATH%"

REM 输出更新后的PATH以确认
ECHO Updated PATH: %PATH%

REM 检查Perl是否可用
perl -v
IF %ERRORLEVEL% NEQ 0 (
    ECHO Perl is not available. Please check your Perl installation.
    PAUSE
    EXIT /B 1
)

REM 切换到OpenSSL_1_1_1d目录
CD /D "%SCRIPT_DIR%OpenSSL_1_1_1d"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to OpenSSL_1_1_1d
    PAUSE
    EXIT /B 1
)

REM 定义构建目录
SET "BUILD_DIR=%SCRIPT_DIR%build\OpenSSL_1_1_1dx64_static"

REM 创建构建目录（如果不存在）
IF NOT EXIST "%BUILD_DIR%" MKDIR "%BUILD_DIR%"

REM 切换到构建目录
CD /D "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to change directory to %BUILD_DIR%
    PAUSE
    EXIT /B 1
)

REM 执行Perl配置脚本
perl "%SCRIPT_DIR%OpenSSL_1_1_1d\Configure" VC-WIN64A no-asm no-shared --prefix="%SCRIPT_DIR%install\OpenSSL_1_1_1dx64_static"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Configuration failed
    PAUSE
    EXIT /B 1
)

REM 使用nmake生成Makefile
nmake
IF %ERRORLEVEL% NEQ 0 (
    ECHO nmake failed
    PAUSE
    EXIT /B 1
)

REM 使用jom进行并行编译
jom -j 8
IF %ERRORLEVEL% NEQ 0 (
    ECHO jom failed
    PAUSE
    EXIT /B 1
)

REM 安装OpenSSL
nmake install_sw
IF %ERRORLEVEL% NEQ 0 (
    ECHO Installation failed
    PAUSE
    EXIT /B 1
)

REM 清理构建目录
ECHO Cleaning up build directory...
CD /D "%SCRIPT_DIR%"
RD /S /Q "%BUILD_DIR%"
IF %ERRORLEVEL% NEQ 0 (
    ECHO Failed to clean up build directory
    PAUSE
    EXIT /B 1
)

ECHO OpenSSL 1.1.1d has been successfully built and installed.
PAUSE
ENDLOCAL